package initialize

import (
	"github.com/gomodule/redigo/redis"
	"log"
	"time"
)

var RedisPool *redis.Pool

func init() {
	// 初始化Redis连接池
	RedisPool = &redis.Pool{
		MaxIdle:     10,
		MaxActive:   100,
		IdleTimeout: 120 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", "localhost:6379")
			if err != nil {
				panic("Failed to connect mysql")
			} else {
				log.Println("Connect redis successfully")
			}
			return c, err
		},
	}

	//conn := RedisPool.Get()
	//defer func(conn redis.Conn) {
	//	if err := conn.Close(); err != nil {
	//		panic(err)
	//	}
	//}(conn)
	//go PersistenceWithRDB(conn)
}

func PersistenceWithRDB(conn redis.Conn) {
	for {
		_, err := conn.Do("BGSAVE")
		if err != nil {
			log.Println("Failed to trigger RDB persistence")
			panic(err)
		}
		log.Println("RDB persistence triggered successfully")
		time.Sleep(30 * time.Minute)
	}
}

func PersistenceWithAOF(conn redis.Conn) {
	for {
		_, err := conn.Do("BGREWRITEAOF")
		if err != nil {
			log.Println("Failed to trigger AOF rewrite")
			panic(err)
		}
		log.Println("AOF rewrite triggered successfully")
		time.Sleep(30 * time.Minute)
	}
}
